<!--
 * @Author: qiye
 * @LastEditors: qiye
 * @description: page description
 * @Date: 2024-01-15 13:44:39
 * @LastEditTime: 2024-02-04 11:06:51
-->
<script setup lang="ts">
import { ikStore } from 'iking-utils'
import Menu from './Menu'
import EmptyContent from './EmptyContent.vue'
import PageEditDialog from './PageEditDialog.vue'
import { pageApi } from '@/MainApp/apis/application'

const props = defineProps({
  application: {
    type: Object,
    default: () => ({})
  }
})
const modules: any = import.meta.glob('@/MainApp/views/**/*.vue')

const { msgError, msgSuccess } = useMessage()

/** 左侧菜单 begin */
const menuRef = ref<any>(null)
const menuState = reactive<any>({
  // 页面列表
  list: [],
  current: null
})
const menuMethods = {
  handleRefresh: (list: any[]) => {
    menuState.list = list

    if (!list.length) {
      //
      menuState.current = null
    }
  },
  handleSelect: async (page: any) => {
    menuState.current = page

    console.log('menuState.currentJson ', menuState.currentJson)
    refreshRenderJson(page.id)
  }
}

const isEmptyApplication = computed(() => menuState.list?.length === 0 ?? true)
/** 左侧菜单 end */

/** 内容区 begin */
// 显示头信息
const headerVisible = computed(() => !!menuState.current)
// 处理创建
const handleCreate = (type: string) => {
  menuRef.value?.submitAdd(type)
}

/** 去编辑视图 */
const toEditView = (page: any, defaultTab: string = 'design') => {
  console.log('to edit', page)
  editMethods.open(page, defaultTab)
}

/**
 * 处理编辑按钮点击
 */
const handleEdit = (page: any = menuState.current) => {
  if (page.type === 'BUSINESS') {
    //
    toEditView(page, 'setting')
  }
  else {
    //
    toEditView(page, 'design')
  }
}

/** 页面编辑对话框 begin */
const editState = reactive<any>({
  visible: false,
  current: null,
  defaultTab: ''
})
const editMethods = {
  open: (page: any, defaultTab: string = 'design') => {
    editState.current = page
    editState.defaultTab = defaultTab
    editState.visible = true
  },
  back: () => {
    editState.visible = false
    menuRef.value?.loadMenu()
    if (editState.current) {
      //
      refreshRenderJson(editState.current.id)
    }
  },
  submit: () => {
    editState.visible = false
    menuRef.value?.loadMenu()
  }
}
/** 页面编辑对话框 end */

/** 页面渲染器 begin */

// 初始化域请求头
const initHeaderArr = () => {
  const headers: any = {}
  // setDomainHeader(headers)
  const result: any [] = Object.keys(headers).map((key: string): any => ({ name: key, value: headers[key] })) ?? []
  return result
}
const headerArr = initHeaderArr()
const globalDatasourceHeaders = ref([
  {
    name: 'Authorization',
    value: useToken()
  },
  {
    name: 'Menu-Id',
    value: ikStore.local.getItem('menuid')
  },
  ...headerArr
])

const isCustomComponent = computed(() => menuState.current?.type === 'BUSINESS')
// 自定义页面
const customPath = computed(() => `/src/MainApp/views/${menuState.current?.component}`)
let CustomComponent = menuState.current?.component ? defineAsyncComponent(() => import(`/src/MainApp/views/${customPath.value}`)) : null
watch(() => customPath.value, (val: any) => {
  if (menuState.current?.component && isCustomComponent.value) {
    //
    CustomComponent = defineAsyncComponent(modules[val])
  }
})

//
const vFormRef = ref<any>(null)
const refreshRenderJson = async (pageId: string) => {
  const res = await pageApi.details(pageId)
  if (!res.success) {
    msgError(res.msg)
    return
  }

  menuState.currentJson = res.data.json ? JSON.parse(res.data.json) : null
  vFormRef.value?.setFormJson(menuState.currentJson)
}
const renderVisible = computed(() => menuState.currentJson && !isCustomComponent.value)

/** 页面渲染器 end */

/** 内容区 end */
</script>

<template>
  <div class="page-manage">
    <Menu
      ref="menuRef"
      class="left-bar"
      :application="props.application"
      @select="menuMethods.handleSelect"
      @refresh="menuMethods.handleRefresh"
      @edit="handleEdit"
    />
    <div class="main-content">
      <div v-if="headerVisible" class="main-content-header">
        <div class="header-left">
          <span>{{ menuState.current?.name }}</span>
        </div>
        <div class="header-right">
          <el-button link type="primary" @click="handleEdit()">编辑表单</el-button>
        </div>
      </div>
      <div class="main-content-body">
        <EmptyContent v-if="isEmptyApplication" @create="handleCreate" />
        <div v-else class="body-card">
          <el-scrollbar class="scroll-bar">
            <v-form-render
              v-if="renderVisible"
              ref="vFormRef"
              class="v-form-render"
              :global-dsv="{}"
              :form-json="menuState.currentJson"
              :global-datasource-headers="globalDatasourceHeaders"
            />
            <CustomComponent v-if="isCustomComponent" />
          </el-scrollbar>
        </div>
      </div>

      <div v-if="editState.visible">
        <PageEditDialog
          v-model="editState.visible"
          :application="application"
          :page="editState.current"
          :default-tab="editState.defaultTab"
          @back="editMethods.back"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.page-manage {
  display: flex;

  .left-bar {
    width: 290px;
    flex-shrink: 0;

    }

    .main-content{
      flex-grow: 1;
      display: flex;
      flex-direction: column;

      .main-content-header{
        height: 44px;
        background-color: var(--color-bg-page-content);
        flex-shrink: 0;
        padding: 0 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .header-left{
          font-size: 16px;
          line-height: 44px;
        }

      }

      .main-content-body{
        flex-grow: 1;
        padding: 28px;

        .body-card{
          background-color: var(--color-bg-page-content);
          height: 100%;
        }

      }

      // .v-form-render{
      //   padding: var(--space-large)
      // }

    }

}
</style>
